/**
 * 234. 回文链表
 * https://leetcode-cn.com/problems/palindrome-linked-list/
 */
public class Solutions_234 {
    public static void main(String[] args) {
//        int[] arr = {1, 2};  // output: false
//        int[] arr = {1, 2, 2, 1};  // output: true
//        int[] arr = {1, 2, 3, 4, 1};  // output: false
        int[] arr = {1, 2, 3, 2, 1};  // output: true

        ListNode head = MyLinkedListUtils.ArrayToListNode(arr);
        boolean result = isPalindrome(head);
        System.out.println(result);
    }

    public static boolean isPalindrome(ListNode head) {
        // 1.快慢指针找到中间结点
        ListNode fast = head, slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 2.反转后半部分链表
        ListNode pre = null;
        while (slow != null) {
            ListNode tempNext = slow.next;
            slow.next = pre;
            pre = slow;
            slow = tempNext;
        }

        // 3.比较两个链表（pre 结点长度一定小于等于 head 结点长度，所以用 pre 来遍历结点）
        while (pre != null) {
            if (pre.val != head.val) {
                return false;
            }
            pre = pre.next;
            head = head.next;
        }
        return true;
    }
}
